import { combineReducers } from 'react';

// 把各个模块reducer合并在一起
import voteReducer from './voteReducer';
import personReducer from './personReducer';

/**
 * 公共状态也开始按照模块进行划分
 * state
 *  + vote
 *    + supNum
 *    + oppNum
 *  + person
 *    + info
 */
const reducer = combineReducers({
  vote: voteReducer,
  person: personReducer
});

export default reducer;

// 原理：并不会把每个板块的reducer合成一个，而是创建一个新的reducer出来；当每一次派发任务的时候，都会执行新的reducer，而我们在这里，把每个板块的reducer都执行，
// 获取每个板块最新的状态，最后替换容器中的总状态
const combineReducers = function combineReducers(reducers) {
  let reducerKeys = Reflect.ownKeys(reducers);
  return function combination(state = {}, action) {
    let nextState = {};
    reducerKeys.forEach(key => {
      let reducer = reducers[key];
      nextState[key] = reducer(state[key], action);
    })
    return nextState;
  }
}